java实现获取文件编码格式,经常用于读取文件内容。 |
您所在的位置:网站首页 › linux 获取文件名的编码格式 › java实现获取文件编码格式,经常用于读取文件内容。 |
1.使用java 语言IO流方式获取文档里面时,由于文档的不同编码方式要采用不同的字符集 eg:如下代码,需要我们用对应文件编码去读取。 InputStreamReader isr = new InputStreamReader(new FileInputStream(file),"utf-8");//file为文件对象 reader = new BufferedReader(isr); String tempString = null; int line = 1; while ((tempString = reader.readLine()) != null) { // 一次读入一行,直到读入null为文件结束 System.out.println("line " + line + ": " + tempString); //localBody=localBody+tempString+"\n"; }吐槽:刚开始也是网上找的别人的代码,见了最多是这个代码,然并没有效果!!! 2.常用的文件编码为UTF-8、GBK、ASCII等。获取文件编码格式的java代码实现如下:(目前个人只测试并使用了UTF-8、GBK、ASCII三种可行,其他格式能否识别不确定。用到的jar包detector放在下面地址!) try { bianMa=getFileCharsetName(file);//调用识别编码格式的逻辑 System.out.println("编码格式为:"+bianMa); } catch (Exception e) { e.printStackTrace(); } /** 获得文件编码 * @param file * @return * @throws Exception */ public static String getFileCharsetName(File file) throws Exception { CodepageDetectorProxy detector = CodepageDetectorProxy.getInstance(); detector.add(new ParsingDetector(false)); detector.add(JChardetFacade.getInstance()); detector.add(ASCIIDetector.getInstance()); detector.add(UnicodeDetector.getInstance()); Charset charset = null; try { charset = detector.detectCodepage(file.toURI().toURL()); } catch (Exception e) { e.printStackTrace(); throw e; } String charsetName = "GBK"; if (charset != null) { if (charset.name().equals("US-ASCII")) { charsetName = "ISO_8859_1"; } else if (charset.name().startsWith("UTF")) { charsetName = charset.name();// 例如:UTF-8,UTF-16BE. }else if(charset.name().equals("GB2312")){ charsetName="GBK"; } } return charsetName;//返回最终的编码格式 }引入依赖: cpdetector cpdetector 1.0 cpdetector antlr 1.0 cpdetector chardet 1.0 cpdetector jargs 1.0
detector包获取链接:https://pan.baidu.com/s/1fUahdV4TyWa9TQrc0ahouQ 提取码:wj5p see you again! |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |